//
//  WDBannerCollectionView.m
//  MyDemos
//
//  Created by iMac on 2018/3/9.
//  Copyright © 2018年 iMac. All rights reserved.
//

#import "WDBannerCollectionView.h"


#pragma mark - WDBannerCollectionViewCell
@interface WDBannerCollectionViewCell : UICollectionViewCell
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImageView *contentImageView;
@end
@implementation WDBannerCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.contentImageView];
    }
    return self;
}
- (void)setImage:(UIImage *)image {
    _image = image;
    self.contentImageView.image = image;
}
- (UIImageView *)contentImageView {
    if (!_contentImageView) {
        _contentImageView = [[UIImageView alloc] init];
        _contentImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        _contentImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _contentImageView;
}
@end


#pragma mark - WDBannerCollectionView
static NSString *wdBannerCollectionViewCellID = @"WDBannerCollectionViewCellID";
@interface WDBannerCollectionView() <UICollectionViewDelegate, UICollectionViewDataSource> {
    NSTimeInterval _repeatTimeinterval;
}

@property (nonatomic, strong) NSArray *images;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIImage *placeHolder;
@end

@implementation WDBannerCollectionView


#pragma mark -initialize
+ (instancetype)bannerViewWithFrame:(CGRect)frame {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = frame.size;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    WDBannerCollectionView *banner = [[self alloc] initWithFrame:frame collectionViewLayout:layout];
    return banner;
}

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {
        [self setupInit];
    }
    return self;
}
- (void)setupInit {
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.bounces = NO;
    self.pagingEnabled = YES;
    self.delegate = self;
    self.dataSource = self;
    _repeatTimeinterval = 0;
    [self registerClass:[WDBannerCollectionViewCell class] forCellWithReuseIdentifier:wdBannerCollectionViewCellID];
}

#pragma mark - delegate & datasource

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    WDBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:wdBannerCollectionViewCellID forIndexPath:indexPath];
    if (self.images.count == 0) {
        cell.image = self.placeHolder;
    }
    else {
        cell.image = self.images[indexPath.row];
//
    }
    return cell;
}
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.images.count == 0) {
        if (self.placeHolder) {
            return 1;
        }
        return 0;
    }
    return self.images.count;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    NSInteger index = offsetX / SCREEN_WIDTH;
    if (index == 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.images.count - 2 inSection:0];
        [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        index = self.images.count - 2;
    }
    else if (index == self.images.count - 1) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        index = 1;
    }
    if (self.currentIndex) {
        self.currentIndex([self getCurrentIndex:index]);
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectedIndex) {
        self.selectedIndex([self getCurrentIndex:indexPath.item]);
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
}
#pragma mark - 
- (void)setBannerImages:(NSArray *)images {
    if (images.count > 1) {
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:images.lastObject];
        [arr addObjectsFromArray:images];
        [arr addObject:images.firstObject];
        self.images = arr.copy;
        [self reloadData];
        [self startTimer];
        [self scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    else {
        self.images = images;
        [self reloadData];
    }
    if (self.currentIndex) {
        self.currentIndex(0);
    }
}
- (void)setRepeatTimeInterval:(NSTimeInterval)time {
    _repeatTimeinterval = time;
}
- (void)setPlaceholder:(UIImage *)image {
    
}

#pragma mark - Timer
- (void)startTimer {
    if (_repeatTimeinterval == 0) {
        _repeatTimeinterval = 1;
    }
    self.timer = [NSTimer timerWithTimeInterval:_repeatTimeinterval target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}


- (void)nextPage {
    NSIndexPath *indexPath = self.indexPathsForVisibleItems.firstObject;
    NSInteger index = indexPath.item;
    if (index == self.images.count - 1) {
        index = 1;
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
    else if (index == 0) {
        index = self.images.count - 2;
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
    index++;
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    if (self.currentIndex) {
        self.currentIndex([self getCurrentIndex:index]);
    }
}
- (NSInteger)getCurrentIndex:(NSInteger)index {
    if (self.images.count < 2) {
        return 0;
    }
    if (index == 0) {
        index = self.images.count - 3;
    }
    else if (index == self.images.count - 1) {
        index = 0;
    }
    else {
        index -= 1;
    }
    return index;
}
- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}
- (void)removeFromSuperview {
    [super removeFromSuperview];
    [self stopTimer];
}
- (void)restart {
    if (self.timer) {
        [self stopTimer];
    }
    [self startTimer];
}

- (void)dealloc {
    NSLog(@"banner dealloc");
    [self stopTimer];
}



@end


